//TODO: request new feed every 30 seconds
//TODO: refresh feed every 1 minute

var isMobile = false;
var currentFeedId;

//switch to feed view
function viewFeeds()
{
	// $("#item-view").hide();
	// $("#feed-view").show();
}

function viewItems(_userID, _feedID)
{
//do nothing
}

function addFeed( _userId )
{
	var feedString = $("#feedString").val();
	if(feedString == "" )
	{
		return;
	}
	$.post("addFeed.php", { userid: _userId, feedstring: feedString}, feedAdded);
	$("#feedString").val("");
}

function feedAdded( _data )
{
	console.log(_data);
	if(_data != "")
	{
		var values = _data.split("|");
		var id = values[0];
		var string = values[1];
		var url = values[2];
		var divString = "<div id='feed-" + id +"'><a class='clickable' onclick='requestFeed(\""+ url +"\"); requestFilters(\"" + id +"\"); currentFeedId=" + id + "'>" + string + "</a> <a class=\"link\" onclick='deleteFeed(\"" + id + "\")'>Delete</a></div>";
		$("#feeds").append(divString);
	}
}

function deleteFeed( _feedID )
{
	console.log("delete feed " + _feedID);
	$.post("deleteFeed.php", { userid : userId, feedid: _feedID}, feedDeleted);
	$("#feed-" + _feedID).remove();
}

function feedDeleted( _data )
{
	console.log(_data);
}

function addFilter()
{
	var feedID = currentFeedId;
	var filterString = $("#filterString").val();
	if ( feedID == null || filterString == "" )
	{
		return;
	}
	$.post("addFilter.php", {userid: userId, feedid: feedID, filterstring: filterString}, filterAdded);
	$("#filterString").val("");
}

function filterAdded( _data )
{
	console.log(_data);
	if(_data != "")
	{
		var values = _data.split(":");
		var id = values[0];
		var string = values[1];
		var divString = "<div id='filter-" + id + "'>" + string + " <a class=\"link\" onclick='deleteFilter(\"" + id + "\")'>Delete</a></div>";
		$("#filters").append(divString);
	}
}

function deleteFilter( _filterID ) 
{
	console.log("deleting filter " + _filterID);
	$.post("deleteFilter.php", {userid: userId, filterid: _filterID}, filterDeleted);
	$("#filter-" + _filterID).remove();
}

function filterDeleted( _data )
{
	console.log(_data);
}

function signIn()
{
	/*
	/ TODO: add functionality for auto sign-in for facebook
	*/
}

function requestFilters( _feedId )
{
	console.log("request filters");
	$.post("getFilters.php", { userid : userId, feedid: _feedId}, filtersReceived);
}

function filtersReceived( _data )
{
	console.log(_data);
	// clear filters
	var filterList = $("#filters");
	filterList.empty();
	// generate filters
	$($(_data).find("filter")).each(
	function (_index)
	{
		var id = $(this).attr("id");
		var string = $(this).attr("string");
		var divString = "<div id='filter-" + id + "'>" + string + " <a class=\"link\" onclick='deleteFilter(\"" + id + "\")'>Delete</a></div>";
		filterList.append(divString);
	});
}